package com.cosmoplat.gfqd.processor;

import com.cosmoplat.gfqd.config.BootStrapConfig;
import com.cosmoplat.gfqd.constants.Constants;
import com.cosmoplat.gfqd.utils.ClearDirectory;
import com.cosmoplat.gfqd.utils.MavenExecutor;

import java.io.File;

/**
 * 基于模板项目创建新项目
 */
public class CreateNewProject {

    private static String ARCHETYPE_GROUPID;
    private static String ARCHETYPE_ARTIFACTID;
    private static String ARCHETYPE_VERSION;

    private static String NACOS_SERVER_ADDR;
    private static String NACOS_NAME_SPACE;
    private static String NEW_ARTIFACTID;


    public static void create(BootStrapConfig config) {

        //拼接mvn命令
        if (config != null) {
            System.out.println("Loaded bootstrap: " + config);
            // Access config values
            ARCHETYPE_GROUPID = config.getCreateProject().getArchetypeGroupId();
            ARCHETYPE_ARTIFACTID = config.getCreateProject().getArchetypeArtifactId();
            ARCHETYPE_VERSION = config.getCreateProject().getArchetypeVersion();
            NACOS_SERVER_ADDR = config.getGenerateProject().getNacosServerAddr();
            NACOS_NAME_SPACE = config.getGenerateProject().getNacosNameSpace();
            NEW_ARTIFACTID = config.getGenerateProject().getNewArtifactId();
        }

        // 清空目标目录
        ClearDirectory.clear(Constants.NEW_PROJECTS);

        //在新目录中创建项目
        MavenExecutor.execute(new File(Constants.NEW_PROJECTS), getGenerateCommand(config).toString());

        //执行instal，把各个项目的api打包
        MavenExecutor.execute(new File(Constants.NEW_PROJECTS + "/" + NEW_ARTIFACTID), "mvn clean install");

    }

    private static StringBuilder getGenerateCommand(BootStrapConfig config) {

        StringBuilder generateCommand = new StringBuilder();
        if (config != null) {
            System.out.println("Loaded bootstrap: " + config);
            generateCommand.append("mvn archetype:generate ")
                    .append("-DgroupId=").append(config.getGenerateProject().getNewGroupId()).append(" ")
                    .append("-DartifactId=").append(config.getGenerateProject().getNewArtifactId()).append(" ")
                    .append("-Dversion=").append(config.getGenerateProject().getNewVersion()).append(" ")
                    .append("-Dpackage=").append(config.getGenerateProject().getNewPackage()).append(" ")
                    .append("-DarchetypeGroupId=").append(ARCHETYPE_GROUPID).append(" ")
                    .append("-DarchetypeArtifactId=").append(ARCHETYPE_ARTIFACTID).append(" ")
                    .append("-DarchetypeVersion=").append(ARCHETYPE_VERSION).append(" ")
                    .append("-DinteractiveMode=false ")
                    .append("-DnacosServerAddr=").append(NACOS_SERVER_ADDR).append(" ")
                    .append("-DnacosNameSpace=").append(NACOS_NAME_SPACE).append(" ")
                    .append("-U");
        }
        System.out.println(generateCommand);

        return generateCommand;
    }
}